package com.milk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.milk.constant.MessageConstant;
import com.milk.constant.StatusConstant;
import com.milk.context.BaseContext;
import com.milk.dto.CommonPageQueryDTO;
import com.milk.dto.EmployeeDTO;
import com.milk.dto.EmployeeLoginDTO;
import com.milk.entity.Employee;
import com.milk.exception.AccountLockedException;
import com.milk.exception.AccountNotFoundException;
import com.milk.exception.BaseException;
import com.milk.exception.PasswordErrorException;
import com.milk.mapper.EmployeeMapper;
import com.milk.result.PageResult;
import com.milk.result.Result;
import com.milk.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;


import java.security.DigestException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 修改密码
     * @param dto
     * @return
     */
    public int editPassword(EmployeeDTO dto) {
        Employee employee = employeeMapper.getByUsername(dto.getUsername());
        String password = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String oldPassword = DigestUtils.md5DigestAsHex(dto.getOldPassword().getBytes());

        if (!Objects.equals(oldPassword,employee.getPassword())) {
            return 0;
        } else  {
            employee.setPassword(password);
            return employeeMapper.updateById(employee);
        }
    }

    /**
     * 新增员工
     * @param dto
     */
    public void insert(Employee dto) {
        Employee employee = employeeMapper.selectById(BaseContext.getCurrentId());
        if (!Objects.equals(employee.getRoles(), "admin")){
            throw new BaseException("你没有新增的权限");
        }

        dto.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        dto.setStatus(1);
        dto.setCreateTime(LocalDateTime.now());

        dto.setCreateUser(BaseContext.getCurrentId());
        employeeMapper.insert(dto);
    }

    /**
     * 修改员工信息
     * @param dto
     */
    public void update(Employee dto) {
        Employee employee = employeeMapper.selectById(BaseContext.getCurrentId());
        if (!Objects.equals(employee.getRoles(), "admin")){
            throw new BaseException("你没有新增的权限");
        }
        dto.setUpdateTime(LocalDateTime.now());

        dto.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(dto);
    }

    /**
     * 删除员工
     * @param ids
     */
    public void deleteByIds(List<Long> ids) {
        Employee employee = employeeMapper.selectById(BaseContext.getCurrentId());
        if (!Objects.equals(employee.getRoles(), "admin")){
            throw new BaseException("你没有新增的权限");
        }
        employeeMapper.deleteByIds(ids);
    }

    /**
     * 查询员工信息
     * @return
     */
    public PageResult selectAll(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查询个人信息
     * @return
     */
    public Employee getEmployeeInfo() {
        return employeeMapper.selectById(BaseContext.getCurrentId());
    }
}
